package com.farm.learn.controller;

import com.farm.learn.domain.Major;
import com.farm.learn.domain.Usermajor;
import com.farm.learn.service.MajorServiceInter;
import com.farm.learn.service.UsermajorServiceInter;
import com.farm.learn.utils.UserMajorLoader;
import com.farm.report.FarmReport;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import com.farm.web.easyui.EasyUiUtils;

import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.authority.domain.Organization;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuerys;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.ResultsHandle;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：用户专业控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/usermajor")
@Controller
public class UsermajorController extends WebUtils {
	private final static Logger log = Logger.getLogger(UsermajorController.class);
	@Resource
	private UsermajorServiceInter userMajorServiceImpl;
	@Resource
	private MajorServiceInter majorServiceImpl;
	@Resource
	private OrganizationServiceInter organizationServiceImpl;

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
		try {
			query = EasyUiUtils.formatGridQuery(request, query);
			DBRule orgidRule = query.getAndRemoveRule("ORGID");
			if (orgidRule != null) {
				Organization org = organizationServiceImpl.getOrganizationEntity(orgidRule.getValue());
				query.addRule(new DBRule("D.TREECODE", org.getTreecode(), "like-"));
			}

			DBRule postRule = query.getAndRemoveRule("POST");
			if (postRule != null) {
				DataQuerys.wipeVirus(postRule.getValue());
				String sql = "select b.userid from ALONE_AUTH_POST a left join ALONE_AUTH_USERPOST b on a.id=b.postid where a.name like '%"
						+ postRule.getValue() + "%' and b.id is not null";
				query.addSqlRule("and b.id in (" + sql + ")");
			}

			DataResult result = userMajorServiceImpl.createUsermajorSimpleQuery(query).search();
			result.runDictionary("2:学习中,3:完成", "PSTATE");
			result.runformatTime("STIME", "yyyy-MM-dd");
			result.runformatTime("ETIME", "yyyy-MM-dd");
			result.runformatTime("LTIME", "yyyy-MM-dd");
			result.runHandle(new ResultsHandle() {
				@Override
				public void handle(Map<String, Object> row) {
					row.put("PROCESS", row.get("PROCESS") + "%");
				}
			});
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(Usermajor entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = userMajorServiceImpl.editUsermajorEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(Usermajor entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = userMajorServiceImpl.insertUsermajorEntity(entity);
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				userMajorServiceImpl.deleteUsermajorEntity(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 加载用户专业学习记录
	 * 
	 * @return
	 */
	@RequestMapping("/loadUserMajors")
	@ResponseBody
	public Map<String, Object> loadUserMajors(String majorid, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			new Thread(new UserMajorLoader(majorid)).start();
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return view.setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/loadUserMajorsProcess")
	@ResponseBody
	public Map<String, Object> loadUserMajorsProcess(HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			return ViewMode.getInstance().putAttr("isRun", UserMajorLoader.isRun())
					.putAttr("all", UserMajorLoader.getAll()).putAttr("i", UserMajorLoader.getI())
					.putAttr("msg", UserMajorLoader.getMessage()).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return view.setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("learn/UsermajorResult");
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(RequestMode pageset, String ids) {
		try {

			List<Major> majors = majorServiceImpl.getAllMajors();

			switch (pageset.getOperateType()) {
			case (0): {// 查看
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", userMajorServiceImpl.getUsermajorEntity(ids))
						.returnModelAndView("learn/UsermajorForm");
			}
			case (1): {// 新增
				return ViewMode.getInstance().putAttr("majors", majors).putAttr("pageset", pageset)
						.returnModelAndView("learn/UsermajorForm");
			}
			case (2): {// 修改
				return ViewMode.getInstance().putAttr("pageset", pageset)
						.putAttr("entity", userMajorServiceImpl.getUsermajorEntity(ids))
						.returnModelAndView("learn/UsermajorForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("learn/UsermajorForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("learn/UsermajorForm");
		}
	}
	
	/**
	 * 下载文件
	 * 
	 * @return
	 */
	@RequestMapping("/exportExcel")
	public void download(String ruleText, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		try {
			DataQuery query = new DataQuery();
			query.setPagesize(5000);
			query.setNoCount();
			query.setRuleText(ruleText);
			Map<String, Object> result = queryall(query, request);
			FarmReport.newInstance("userMajor.xls").addParameter("result", result.get("rows"))
					.addParameter("message",
							query.getPagesize() <= ((List) result.get("rows")).size()
									? "本报表仅展示前" + query.getPagesize() + "条记录"
									: "")
					.generateForHttp(response, "userHour");
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}
}
